package com.hershel.userservice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hershel.hershelcommonpackage.exception.DataBaseQueryNullException;
import com.hershel.userservice.entity.User;
import com.hershel.userservice.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.UUID;

@Service
public class UserService implements UserDetailsService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;

    public List<User> test() {
        List<User> user = userMapper.queryAll();
        return user;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
//        return new UserDetailsImpl(username);
        return null;
    }

    public void registerUser(String username, String rawPassword) {
        String encryptPassword = passwordEncoder.encode(rawPassword);
        //todo：保存用户信息到数据库，包括加密后的密码
    }

    /**
     * 登录
     *
     * @param username    用户名
     * @param rawPassword 密码
     * @return boolean
     */
    public boolean login(String username, String rawPassword) {
        LOGGER.info("username:{},rawPassword:{}",username,rawPassword);
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = userMapper.selectOne(queryWrapper);
        LOGGER.info("user:{}",user);
        if(StringUtils.isEmpty(user)){
            throw new DataBaseQueryNullException();
        }
        boolean result = rawPassword.equals(user.getPassword());
        LOGGER.info("密码比对结果为：{}",result);
        return result;
    }
}
